# -*- coding:utf-8 -*- #

#引入上层目录模块方法
import sys
sys.path.append("..")

import socket
from logger.logger import getlogger
from conf import configure

from time import sleep

class _Connection(object):
    """docstring for _Connection"""
    def __init__(self, addr):
        super(_Connection, self).__init__()
        self.addr = addr
        socket.setdefaulttimeout(10)

    def create(self, family, types):

        s = socket.socket(family, types)
        try:
            #print "连接地址==",self.addr
            s.connect(self.addr)
            return s
        except socket.error:
            getlogger(configure.logger_path).error("connection refuse:%s" % str(self.addr))
            #raise socket.error("connection refuse:%s" % str(self.addr))
            
            #print "连接失败，等待重试"
            return False
              
        #return s


class LongConnection(_Connection):
    """docstring for LongConnection"""
    def __init__(self, addr):
        super(LongConnection, self).__init__(addr)
        self.conn = None

    def __del__(self):
        self.close()

    def close(self):
        if self.conn:
            self.conn.close()


    def check_is_alive(self):
        if self.conn:
            return True
        return False

    def send(self, msg):
        if (not self.conn):
            self.conn = self.create(socket.AF_INET, socket.SOCK_STREAM)
        self.conn.send(msg)

    def recv(self):
        msg = self.conn.recv(1000)
        return msg
            #print msg
            #print json.loads(msg)

class ShortConnection(_Connection):
    """docstring for ShortConnection"""
    def __init__(self, addr):
        super(ShortConnection, self).__init__(addr)
        self.addr = addr

    def check_is_alive(self):

        self.conn = self.create(socket.AF_INET, socket.SOCK_STREAM)

    def send(self, msg):

        try:
            if not self.conn:
                self.check_is_alive()
        except:
            #服务器断开后 或 连接失败
            self.check_is_alive()

            
        try:
            print "消息=",msg
            self.conn.send(msg)
            #self.conn.close()
        except:
            self.conn = False

